/**
 * 视频生成系统 - 主要JavaScript功能
 * 实现文件上传、进度显示、任务管理等前端交互
 */

// 全局变量
let socket = null;
let currentTaskId = null;
let uploadTaskId = null;
let taskCheckInterval = null;

// DOM加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeApp();
});

/**
 * 初始化应用
 */
function initializeApp() {
    // 初始化Socket.IO连接
    initSocketIO();

    // 绑定事件监听器
    bindEventListeners();

    // 启动任务列表自动刷新
    startTaskListRefresh();

    console.log('视频生成系统已初始化');
}

/**
 * 初始化Socket.IO连接
 */
function initSocketIO() {
    if (typeof io === 'undefined') {
        console.error('Socket.IO未加载');
        return;
    }

    socket = io();

    // 连接事件
    socket.on('connect', function() {
        console.log('已连接到服务器');
        showNotification('已连接到服务器', 'success');
    });

    socket.on('disconnect', function() {
        console.log('与服务器断开连接');
        showNotification('与服务器断开连接', 'warning');
    });

    // 任务进度更新
    socket.on('progress', function(data) {
        if (data.task_id === currentTaskId) {
            updateProgress(data.progress, data.status);
            addLogEntry(data.status);
        }
    });

    // 任务完成
    socket.on('completed', function(data) {
        if (data.task_id === currentTaskId) {
            updateProgress(100, '完成');
            addLogEntry('任务已完成');
            showResult(data.task_id);

            // 重置生成按钮
            resetGenerateButton();
            showNotification('视频生成完成！', 'success');
        }
    });

    // 任务错误
    socket.on('error', function(data) {
        if (data.task_id === currentTaskId) {
            addLogEntry('错误: ' + data.error, 'error');
            showError('生成失败: ' + data.error);

            // 重置生成按钮
            resetGenerateButton();
        }
    });

    // 任务状态更新
    socket.on('status', function(data) {
        if (data.task_id === currentTaskId) {
            updateProgress(data.progress, data.current_step);
        }
    });
}

/**
 * 绑定事件监听器
 */
function bindEventListeners() {
    // 上传表单
    const uploadForm = document.getElementById('uploadForm');
    if (uploadForm) {
        uploadForm.addEventListener('submit', handleFileUpload);
    }

    // 生成按钮
    const generateBtn = document.getElementById('generateBtn');
    if (generateBtn) {
        generateBtn.addEventListener('click', handleGenerateVideo);
    }

    // 文件输入
    const fileInput = document.getElementById('fileInput');
    if (fileInput) {
        fileInput.addEventListener('change', handleFileSelect);
    }
}

/**
 * 处理文件选择
 */
function handleFileSelect(event) {
    const file = event.target.files[0];
    const uploadResult = document.getElementById('uploadResult');

    if (!file) {
        return;
    }

    // 验证文件类型
    if (!file.name.endsWith('.md')) {
        showError('仅支持 Markdown (.md) 格式文件');
        event.target.value = '';
        return;
    }

    // 验证文件大小 (16MB)
    const maxSize = 16 * 1024 * 1024;
    if (file.size > maxSize) {
        showError('文件大小不能超过 16MB');
        event.target.value = '';
        return;
    }

    // 显示文件信息
    if (uploadResult) {
        uploadResult.style.display = 'block';
        uploadResult.className = 'alert alert-info';
        uploadResult.innerHTML = `
            <i class="fas fa-info-circle me-2"></i>
            已选择文件: ${file.name} (${formatFileSize(file.size)})
        `;
    }
}

/**
 * 处理文件上传
 */
function handleFileUpload(event) {
    event.preventDefault();

    const fileInput = document.getElementById('fileInput');
    const uploadBtn = document.getElementById('uploadBtn');

    if (!fileInput.files[0]) {
        showError('请选择一个文件');
        return;
    }

    // 准备表单数据
    const formData = new FormData();
    formData.append('file', fileInput.files[0]);

    // 更新按钮状态
    uploadBtn.disabled = true;
    uploadBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>上传中...';

    // 发送上传请求
    fetch('/api/upload', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.task_id) {
            uploadTaskId = data.task_id;
            showUploadResult(data);
            enableGenerateButton();
            showNotification('文件上传成功', 'success');
        } else {
            showError(data.error || '上传失败');
        }
    })
    .catch(error => {
        console.error('上传错误:', error);
        showError('上传失败: ' + error.message);
    })
    .finally(() => {
        // 重置按钮
        uploadBtn.disabled = false;
        uploadBtn.innerHTML = '<i class="fas fa-cloud-upload-alt me-2"></i>上传文件';
    });
}

/**
 * 处理视频生成
 */
function handleGenerateVideo() {
    if (!uploadTaskId) {
        showError('请先上传文件');
        return;
    }

    // 收集配置
    const config = {
        task_id: uploadTaskId,
        quality: document.getElementById('quality')?.value || 'standard',
        theme: document.getElementById('theme')?.value || 'dark',
        resolution: document.getElementById('resolution')?.value || '1920x1080',
        fps: parseInt(document.getElementById('fps')?.value || '30')
    };

    // 更新按钮状态
    const generateBtn = document.getElementById('generateBtn');
    generateBtn.disabled = true;
    generateBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>生成中...';

    // 发送生成请求
    fetch('/api/generate', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(config)
    })
    .then(response => response.json())
    .then(data => {
        if (data.task_id) {
            currentTaskId = data.task_id;
            showProgress(data.task_id);

            // 连接任务状态更新
            if (socket) {
                socket.emit('check_status', {task_id: data.task_id});
            }

            showNotification('开始生成视频', 'info');
        } else {
            showError(data.error || '生成失败');
            resetGenerateButton();
        }
    })
    .catch(error => {
        console.error('生成错误:', error);
        showError('生成失败: ' + error.message);
        resetGenerateButton();
    });
}

/**
 * 显示上传结果
 */
function showUploadResult(data) {
    const result = document.getElementById('uploadResult');
    if (!result) return;

    result.style.display = 'block';
    result.className = 'alert alert-success';
    result.innerHTML = `
        <i class="fas fa-check-circle me-2"></i>
        上传成功: ${data.filename}
    `;
}

/**
 * 启用生成按钮
 */
function enableGenerateButton() {
    const generateBtn = document.getElementById('generateBtn');
    if (generateBtn) {
        generateBtn.disabled = false;
    }
}

/**
 * 重置生成按钮
 */
function resetGenerateButton() {
    const generateBtn = document.getElementById('generateBtn');
    if (generateBtn) {
        generateBtn.disabled = false;
        generateBtn.innerHTML = '<i class="fas fa-video me-2"></i>开始生成视频';
    }
}

/**
 * 显示进度
 */
function showProgress(taskId) {
    const progressCard = document.getElementById('progressCard');
    const taskIdElement = document.getElementById('taskId');
    const logOutput = document.getElementById('logOutput');

    if (progressCard) {
        progressCard.style.display = 'block';
    }

    if (taskIdElement) {
        taskIdElement.textContent = `任务ID: ${taskId.substring(0, 8)}...`;
    }

    if (logOutput) {
        logOutput.innerHTML = '<div class="small">开始处理...</div>';
        logOutput.scrollTop = logOutput.scrollHeight;
    }
}

/**
 * 更新进度
 */
function updateProgress(progress, status) {
    const progressBar = document.getElementById('progressBar');
    const progressText = document.getElementById('progressText');
    const currentStep = document.getElementById('currentStep');

    if (progressBar) {
        progressBar.style.width = progress + '%';
    }

    if (progressText) {
        progressText.textContent = progress + '%';
    }

    if (currentStep) {
        currentStep.textContent = status;
    }
}

/**
 * 添加日志条目
 */
function addLogEntry(message, type = 'info') {
    const logOutput = document.getElementById('logOutput');
    if (!logOutput) return;

    const time = new Date().toLocaleTimeString();
    const logEntry = document.createElement('div');
    logEntry.className = 'small';

    const colorClass = type === 'error' ? 'text-danger' : 'text-light';
    logEntry.innerHTML = `<span class="text-muted">[${time}]</span> <span class="${colorClass}">${message}</span>`;

    logOutput.appendChild(logEntry);
    logOutput.scrollTop = logOutput.scrollHeight;
}

/**
 * 显示结果
 */
function showResult(taskId) {
    const resultCard = document.getElementById('resultCard');
    const resultMessage = document.getElementById('resultMessage');
    const downloadBtn = document.getElementById('downloadBtn');

    if (resultMessage) {
        resultMessage.innerHTML = '<i class="fas fa-check-circle me-2"></i>视频生成完成！';
    }

    if (downloadBtn) {
        downloadBtn.href = `/api/download/${taskId}`;
    }

    if (resultCard) {
        resultCard.style.display = 'block';
        resultCard.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
    }
}

/**
 * 显示错误
 */
function showError(message) {
    const result = document.getElementById('uploadResult');
    if (!result) return;

    result.style.display = 'block';
    result.className = 'alert alert-danger';
    result.innerHTML = `<i class="fas fa-exclamation-circle me-2"></i>${message}`;

    // 3秒后自动隐藏
    setTimeout(() => {
        result.style.display = 'none';
    }, 5000);
}

/**
 * 显示通知
 */
function showNotification(message, type = 'info') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `alert alert-${type} position-fixed`;
    notification.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    notification.innerHTML = `
        <i class="fas fa-${getIconForType(type)} me-2"></i>
        ${message}
    `;

    document.body.appendChild(notification);

    // 显示动画
    setTimeout(() => {
        notification.style.opacity = '1';
        notification.style.transform = 'translateX(0)';
    }, 10);

    // 3秒后自动隐藏
    setTimeout(() => {
        notification.style.opacity = '0';
        notification.style.transform = 'translateX(100%)';
        setTimeout(() => {
            document.body.removeChild(notification);
        }, 300);
    }, 3000);
}

/**
 * 根据类型获取图标
 */
function getIconForType(type) {
    const icons = {
        'success': 'check-circle',
        'danger': 'exclamation-circle',
        'warning': 'exclamation-triangle',
        'info': 'info-circle'
    };
    return icons[type] || 'info-circle';
}

/**
 * 启动任务列表自动刷新
 */
function startTaskListRefresh() {
    fetchTasks();

    // 每30秒刷新一次
    setInterval(fetchTasks, 30000);
}

/**
 * 获取任务列表
 */
function fetchTasks() {
    fetch('/api/tasks')
    .then(response => response.json())
    .then(data => {
        updateTaskList(data.tasks || []);
    })
    .catch(error => {
        console.error('获取任务列表失败:', error);
    });
}

/**
 * 更新任务列表
 */
function updateTaskList(tasks) {
    const taskList = document.getElementById('taskList');
    if (!taskList) return;

    if (tasks.length === 0) {
        taskList.innerHTML = '<div class="text-muted">暂无任务</div>';
        return;
    }

    let html = '<div class="table-responsive">';
    html += '<table class="table table-hover">';
    html += '<thead><tr><th>任务ID</th><th>文件名</th><th>状态</th><th>进度</th><th>开始时间</th></tr></thead>';
    html += '<tbody>';

    tasks.forEach(task => {
        const statusBadge = getStatusBadge(task.status);
        const progress = task.progress || 0;

        html += '<tr>';
        html += `<td><code>${task.task_id.substring(0, 8)}...</code></td>`;
        html += `<td>${task.file}</td>`;
        html += `<td>${statusBadge}</td>`;
        html += `<td>
            <div class="progress" style="height: 20px;">
                <div class="progress-bar" style="width: ${progress}%">${progress}%</div>
            </div>
        </td>`;
        html += `<td>${formatTime(task.start_time)}</td>`;
        html += '</tr>';
    });

    html += '</tbody></table></div>';
    taskList.innerHTML = html;
}

/**
 * 获取状态徽章
 */
function getStatusBadge(status) {
    const badges = {
        'processing': '<span class="badge bg-primary">处理中</span>',
        'completed': '<span class="badge bg-success">已完成</span>',
        'failed': '<span class="badge bg-danger">失败</span>',
        'pending': '<span class="badge bg-warning">等待中</span>'
    };
    return badges[status] || '<span class="badge bg-secondary">未知</span>';
}

/**
 * 格式化时间
 */
function formatTime(timeStr) {
    if (!timeStr) return '-';
    const date = new Date(timeStr);
    return date.toLocaleString();
}

/**
 * 格式化文件大小
 */
function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
}

/**
 * 检查浏览器支持
 */
function checkBrowserSupport() {
    const warnings = [];

    // 检查File API
    if (!window.File || !window.FileReader) {
        warnings.push('您的浏览器不支持文件上传功能');
    }

    // 检查WebSocket
    if (!window.WebSocket) {
        warnings.push('您的浏览器不支持实时更新功能');
    }

    if (warnings.length > 0) {
        showNotification('警告: ' + warnings.join(', '), 'warning');
    }
}

// 页面加载完成后检查浏览器支持
window.addEventListener('load', function() {
    checkBrowserSupport();
});
